package edu.bit.water.util;

import com.squareup.okhttp.*;
import edu.bit.water.controller.MetaEvaWsrcInfoController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(MetaEvaWsrcInfoController.class);

    public static Response formJsonPost(String url, String jsonString) {

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setConnectTimeout(20, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(20, TimeUnit.MINUTES);
        okHttpClient.setWriteTimeout(20, TimeUnit.SECONDS);
        MediaType json = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(json, jsonString);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            return okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            logger.error("调用接口失败");
            return null;
        }

    }

    public static Response formJsonGet(String url) {

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setConnectTimeout(20, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(20, TimeUnit.MINUTES);
        okHttpClient.setWriteTimeout(20, TimeUnit.SECONDS);
        MediaType json = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try {
            return okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            logger.error("调用接口失败");
            return null;
        }

    }
}